package org.opsli.plugins.GoogleAuthenticator;
import cn.hutool.extra.qrcode.QrCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.base.result.ResultWrapper;
import org.opsli.api.wrapper.system.user.UserModel;
import org.opsli.core.utils.UserUtil;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;

/**
 * 项目启动类
 *
 * @author wuge
 */
@Slf4j
@RestController
@SpringBootApplication
public class Main {


    private HttpServletResponse response;

    /**
     * 生成 Google 密钥，两种方式任选一种
     */
    @GetMapping("getSecretKey")
    public String getSecretKey() {

        return GoogleAuthenticator.getSecretKey();
    }

    /**
     * 生成二维码，APP直接扫描绑定，两种方式任选一种
     */
    @GetMapping("getQrText")
    public ResultWrapper<?> getQrcode(HttpServletResponse response) {
        this.response = response;
        String secretKey;
        secretKey = GoogleAuthenticator.getSecretKey();
        // 生成二维码内容
        String qrCodeText = GoogleAuthenticator.getQrCodeText(secretKey, "HarbourX/"+UserUtil.getUser().getEmail(), "");
      return ResultWrapper.getSuccessResultWrapper(qrCodeText);
    }

    /**
     * 获取code
     */
    @GetMapping("getCode")
    public String getCode() {
        return GoogleAuthenticator.getCode(UserUtil.getUser().getSecretKey());
    }

    /**
     * 验证 code 是否正确
     */
    @GetMapping("checkCode")
    public ResultWrapper<Boolean> checkCode(@RequestParam("code") String code) {
        log.info(code);
        if (GoogleAuthenticator.checkCode(UserUtil.getUser().getSecretKey(), Long.parseLong(code), System.currentTimeMillis())){

            //不管是登录还是首次绑定 都设置绑定成功  更新用户。刷新缓存。
            //如果未开启 则开启、如果已开启则直接返回
            if (UserUtil.getUser().getIs2fa()==0){
                UserUtil.getUser().setIs2fa(1);
                UserModel userModel = UserUtil.getUser();
                userModel.setIs2fa(1);
                UserUtil.updateUser(userModel);
                return ResultWrapper.getSuccessResultWrapperByMsg("Success");
            }


            return ResultWrapper.getSuccessResultWrapperByMsg("Success");
        }else {
            return ResultWrapper.getCustomResultWrapper(500,"error");
        }

    }
}